import { type GoGoAST } from "gogocode";
import { CommonParams } from "../types";
import { updateLocalesFile } from "../utils/file";
import { hasChinese, isChinese, isInProps } from "../utils/check";

const parseScript = ({
  sfcAst,
  CONFIG,
  logger,
  filePath,
}: CommonParams & { sfcAst: GoGoAST }): GoGoAST => {
  const { I18N_FUNC, CHINESE_REGEX: CRG } = CONFIG;
  const getKey = (text: string) =>
    updateLocalesFile({
      text,
      CONFIG,
      logger,
      filePath,
    });
  return sfcAst
    .find(`<script></script>`)
    .find("$_$:$_$1")
    .each((el) => {
      const prop = el.match[0][0];
      const val = el.match[1][0];
      if (hasChinese(val.value, CRG) && !isInProps(el)) {
        if (val.node.type === "StringLiteral") {
          const key = getKey(val.value);
          const newStr = `${prop.value}: this.${I18N_FUNC}('${key}')`;
          // 替换需使用replace方法，replaceBy方法可能会添加额外的换行
          el.replace("$_$:$_$1", () => newStr);
        }
      }
    })
    .root()
    .find(`<script></script>`)
    .find("$_$=$_$1")
    .each((el) => {
      const prop = el.match[0][0];
      const val = el.match[1][0];
      if (hasChinese(val.value, CRG) && !isInProps(el)) {
        if (val.node.type === "StringLiteral") {
          const key = getKey(val.value);
          const newStr = `${prop.value} = this.${I18N_FUNC}('${key}')`;
          // 替换需使用replace方法，replaceBy方法可能会添加额外的换行
          el.replace("$_$=$_$1", () => newStr);
        }
      }
    })
    .root();
};

export default parseScript;
